package com.frinder.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by kiktech on 2017/8/4.
 * <p>
 * 管理客户端 handler
 */
@Slf4j
public class ClientManagerHandler extends ChannelInboundHandlerAdapter {

    private ChannelGroup channels;

    public ClientManagerHandler(ChannelGroup channels) {
        super();
        this.channels = channels;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel client = ctx.channel();
        log.info("{} Connecting!", client.remoteAddress());
        // 将新客户端放入channel group中
        channels.add(client);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel client = ctx.channel();
        log.info("{} Left!", client.remoteAddress());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel client = ctx.channel();
        log.info("{} Connected!", client.remoteAddress());
        // 客户端连接成功后反馈
        ctx.writeAndFlush(new NettyResponse().success());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel client = ctx.channel();
        log.info("{} Leaving!", client.remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error(cause.getMessage(), cause);
        ctx.close();
    }

}
